<?php

class SystemPresenter extends AdminPresenter{

	// TODO documentation


	/**
	 * Start lifecycle presenter
	 *
	 * @return void
	 */
	protected function startup()
	{
		parent::startup();
	}

	/**
	 * Settings for all render
	 *
	 * @return void
	 */
	protected function beforeRender()
	{

		$user = Environment::getUser();
		$id = Presenter::getRequest()->params["id"];
		$action = Presenter::getRequest()->params["action"];
		
		$data = Environment::getUser()->getIdentity()->getData();
		$id_user = $data["id_user"];
		
		if($action == "editUser" && ($id == $id_user) || $action == "viewUsers"){
			
		}else{
		
		if(!$user->isInRole("admin") && !$user->isInRole("superAdmin")){
			$this->setLayout("noPermission");
		}
		}
	}

	/**
	 * Render default action
	 *
	 * @return void
	 */
	public function renderDefault($id){
		
		$this->template->title = "Správa systému";

	}

	public function actionViewMenu($id, $ident){

		$this->template->title = "Správa položek menu";
		$this->template->menu_view = $this->system->getMenu(true);

	}

	public function actionReorder($id, $ident){

		if($id=="dolu"){
			$action = 1;
		}

		if($id=="nahoru"){
			$action = -1;
		}

		$item = $this->system->loadMenuItemById($ident);
		$edit_item = $item[0]["id_menu"];

		$menu = $this->system->getMenuLeaf($item[0]["parent"]);

		$count = count($menu);
		for($i=0;$i<$count;$i++){
			if($menu[$i]["id_menu"]==$ident) $index = $i;
		}

		$edit_item_2 = $menu[$index+$action]["id_menu"];

		if(is_numeric($edit_item) && is_numeric($edit_item_2)){

			$first = $this->system->loadMenuItemById($edit_item);
			$second = $this->system->loadMenuItemById($edit_item_2);

			$tmp = $first[0]["order"];
			$first[0]["order"] = $second[0]["order"];
			$second[0]["order"] = $tmp;

			$this->system->saveMenuItem((array) $first[0]);
			$this->system->saveMenuItem((array) $second[0]);

		}

		$this->redirect("System:viewMenu");

	}

	public function actionEditMenuItem($id){

		$this->template->title = "Editace položky";
		$this->template->form = $this->getComponent('editMenuItem');

	}

	public function actionDeleteMenuItem($id){

		$this->system->deleteMenuItem($id);
		$this->flashMessage("Položka menu byla smazána.", 'ok');
		$this->redirect('System:viewMenu');

	}

	protected function createComponentEditMenuItem(){

		$request = $this->presenter->getRequest();

		$item = $this->system->loadMenuItemById($request->params["id"]);

		$modules = $this->system->getModulesToSelect();
		$menu[0] = "Žádná";
		$menu["Menu"] = $this->system->getMenutoSelect();

		$form = new AppForm;

		$form->addText('name', 'Název:')->setDefaultValue($item[0]["name"])
		->addRule(Form::FILLED, 'Název musí být vyplněn')
		->addCondition(Form::FILLED);
		
		$form->addText('seo_title', 'Nadpis:')->setDefaultValue($item[0]["seo_title"]);
		$form->addText('seo_description', 'Description:')->setDefaultValue($item[0]["seo_description"]);
		
		$form->addSelect("id_module", "Modul", $modules)->setDefaultValue($item[0]["id_module"]);
		$form->addSelect("parent", "Nadřazená", $menu)->setDefaultValue($item[0]["parent"]);

		$form->addCheckbox("show_in_menu", "Zobrazit v menu")->setDefaultValue($item[0]["show_in_menu"]);
		$form->addCheckbox("start", "Výchozí stránka")->setDefaultValue($item[0]["start"]);
		
		$form->addHidden("id_menu")->setDefaultValue($item[0]["id_menu"]);

		$form->addSubmit('confirm', 'Uložit')->getControlPrototype()->class('submit');
		$form->onSubmit[] = array($this, 'editMenuItemFormSubmitted');
		
		// pridame boxy
		if(is_numeric($item[0]["id_menu"])){
			$modules = $this->system->getBoxInMenuByIdMenu($item[0]["id_menu"]);
			
			$form->addGroup("Boxy");
			foreach($modules as $m){
				$form->addCheckbox("box_in_module__{$m["id_box_in_menu"]}", $m["name"])->setDefaultValue($m["enable"]);
			}
		}

		return $form;
	}

	public function editMenuItemFormSubmitted(AppForm $form){
		$values = $form->getValues();

		$values["name_seo"] = $this->createSeo($values["name"]);

		foreach($values as $key => $v){

			if(is_numeric(strpos($key, "box_in_module"))){
				$ex = explode("__", $key);

				$box_in_menu[] = array(
								"id_box_in_menu" => $ex[1],
								"enable" => empty($v) ? 0 : 1
									);
				
				unset($values[$key]);
			}
		}
		
		if(!empty($values["name"])){
			$this->system->saveMenuItem($values);
			if(is_array($box_in_menu)) $this->system->saveBoxInMenu($box_in_menu);
			$this->flashMessage("Položka menu byla úspěšně uložena.", 'ok');
			$this->redirect('System:viewMenu');
		}

	}

	// TODO predelat na actions, dodelat refresh modulu, kvuli parametrum napriklad
	public function actionViewModules($id, $ident){

		if($id == "register"){
			$modules = $this->system->loadModulesFromDir();

			foreach($modules as $module){

				if(!$this->system->isModulRegistered($module["name"]) && !empty($module["name"])){

					if(file_exists(WWW_DIR . "/app/modules/" . $module["name"] . ".php")) require(WWW_DIR . "/app/modules/" . $module["name"] . ".php");
					else require(WWW_DIR . "/app/modules/" . $module["name"] . "/" . $module["name"] . ".php");
					
					$object = new $module["name"];

					$info = $object->getInfo();
					
					$object->getSql();

					$id_module = $this->system->registerModule($info);
					
					if(method_exists($object, "getSearch")){
						$search = $object->getSearch();
						
						// registrace vyhledavani
						$this->system->registerSearch($search, $id_module);
					}
					
					$this->flashMessage("Modul {$info["name"]} byl úspěšně zaregistrován do systému.", "ok");

				}
			}

			$this->flashMessage("Po zaregistrování musíte modul nejprve aktivovat, poté se Vám bude zobrazovat ve správě položek menu.", "info");
			$this->redirect("System:viewModules");
		}

		if($id == "active"){

			$this->system->toggleModule($ident);
			$this->flashMessage("Modul byl upraven.", "ok");
			$this->redirect("System:viewModules");
		}
		
		if($id == "registerSearch"){
			
			$modules = $this->system->fetchModules();
			
			$citac = 0;
			foreach($modules as $module){
				
				if(!$this->system->isSearchRegistered($module["id_module"])){
					if(file_exists(WWW_DIR . "/app/modules/" . $module["presenter"] . ".php")) require(WWW_DIR . "/app/modules/" . $module["presenter"] . ".php");
					else require(WWW_DIR . "/app/modules/" . $module["presenter"] . "/" . $module["presenter"] . ".php");
					
	
					$object = new $module["presenter"];
					
					if(method_exists($object, "getSearch")){
						$search = $object->getSearch();
						
						// registrace vyhledavani
						$this->system->registerSearch($search, $module["id_module"]);
						$citac++;
					}
				}
			}
			$this->flashMessage("Doregistrováno celkem " . $citac . " modulů.", "ok");
		}

		$this->template->title = "Správa modulů";
		$this->template->modules = $this->system->getModules();

	}


	public function actionViewUsers(){

		$this->template->title = "Správa uživatelů";
		$this->template->users = $this->system->getUsers();

	}

	public function actionEditUser(){

		$this->template->title = "Editace uživatele";
		$this->template->form = $this->getComponent('editUser');

	}

	public function actionAddUser(){

		$this->template->title = "Přidání uživatele";
		$this->template->form = $this->getComponent('addUser');

	}

	public function actionDeleteUser(){

		$item = $this->presenter->params["id"];

		$this->system->deleteUser($item);

		$this->flashMessage("Uživatel byl smazán.", "ok");
		$this->redirect("System:viewUsers");

	}

	protected function createComponentEditUser($id){

		$request_id = $this->presenter->params["id"];

		$item = $this->system->loadUser($request_id);

		$form = new AppForm;

		$form->addText('real_name', 'Jméno:')->setDefaultValue($item[0]["real_name"])
		->addRule(Form::FILLED, 'Jméno musí být vyplněno.')
		->addCondition(Form::FILLED);

		$form->addText("login","Login:")->setDefaultValue($item[0]["login"])
		->addRule(Form::FILLED, 'Login musí být vyplněn.')
		->addCondition(Form::FILLED);

		$form->addPassword("password","Heslo");
		$form->addPassword("password_again","Heslo");

		$form->addSelect("role", "Oprávnění", array("admin"=>"Administrátor","manager"=>"Správce dat"))->setDefaultValue($item[0]["role"]);

		$form->addCheckBox("change_pwd", "Změnit heslo");

		$form->addHidden("id_user")->setDefaultValue($item[0]["id_user"]);

		$form->addSubmit('confirm', 'Uložit')->getControlPrototype()->class('submit');
		$form->onSubmit[] = array($this, 'editUserFormSubmitted');

		return $form;
	}

	public function editUserFormSubmitted(AppForm $form){
		$values = $form->getValues();

		if($values["change_pwd"]){
			if(!empty($values["password"]) && ($values["password"]==$values["password_again"])){
				$values["password"] = sha1($values["password"]);
			}else{
				$this->flashMessage("Opsali jste špatně heslo, nebo je pole pro heslo prázdné.", "warning");
				$this->redirect("System:editUser", array('id'=>$values["id_user"]));
			}
		}else{
			unset($values["password"]);
		}

		unset($values["password_again"]);
		unset($values["change_pwd"]);

		$this->system->editUser($values);
		$this->flashMessage("Údaje o uživateli byly uloženy.", 'ok');
		$this->redirect('System:viewUsers');

	}

	protected function createComponentAddUser($id){

		$request_id = $this->presenter->params["id"];

		$item = $this->system->loadUser($request_id);

		$form = new AppForm;

		$form->addText('real_name', 'Jméno:')->setDefaultValue($item[0]["real_name"])
		->addRule(Form::FILLED, 'Jméno musí být vyplněno.')
		->addCondition(Form::FILLED);

		$form->addText("login","Login:")->setDefaultValue($item[0]["login"])
		->addRule(Form::FILLED, 'Login musí být vyplněn.')
		->addCondition(Form::FILLED);

		$form->addPassword("password","Heslo");
		$form->addPassword("password_again","Heslo");

		$form->addSelect("role", "Oprávnění", array("admin"=>"Administrátor","manager"=>"Správce dat"))->setDefaultValue($item[0]["role"]);

		$form->addHidden("id_user")->setDefaultValue($item[0]["id_user"]);

		$form->addSubmit('confirm', 'Uložit')->getControlPrototype()->class('submit');
		$form->onSubmit[] = array($this, 'addUserFormSubmitted');

		return $form;
	}

	public function addUserFormSubmitted(AppForm $form){
		$values = $form->getValues();

		if(!(!empty($values["password"]) && ($values["password"]==$values["password_again"]))){
			$this->flashMessage("Opsali jste špatně heslo, nebo je pole pro heslo prázdné.", "warning");
			return false;
		}

		$values["password"] = sha1($values["password"]);
		unset($values["password_again"]);

		$this->system->addUser($values);
		$this->flashMessage("Údaje o uživateli byly uloženy.", 'ok');
		$this->redirect('System:viewUsers');

	}

	public function actionViewLanguages(){

		$this->template->languages = $this->system->getLanguages();
		$this->template->title = "Správa jazyků";
		
	}
	
	public function actionEditLanguage(){
		
		$this->template->title = "Editace jazyku";
		$this->template->form = $this->getComponent("editLanguage");
		
	}
	
	public function actionDeleteLanguage(){
		
		$item = $this->presenter->params["id"];

		$this->system->deleteLanguage($item);

		$this->flashMessage("Jazyk byl smazán.", "ok");
		$this->redirect("System:viewLanguages");
		
	}

	protected function createComponentEditLanguage(){

		$request = $this->presenter->getRequest();

		$item = $this->system->getLanguage($request->params["id"]);

		$form = new AppForm;

		$form->addText('name', 'Název:')->setDefaultValue($item[0]["name"])
		->addRule(Form::FILLED, 'Název musí být vyplněn')
		->addCondition(Form::FILLED);

		$form->addText('abbr', 'Zkratka:')->setDefaultValue($item[0]["abbr"])
		->addRule(Form::FILLED, 'Zkratka musí být vyplněna')
		->addCondition(Form::FILLED);

		$form->addCheckbox("default", "Výchozí jazyk")->setDefaultValue($item[0]["default"]);

		$form->addHidden("id_language")->setDefaultValue($item[0]["id_language"]);

		$form->addSubmit('confirm', 'Uložit')->getControlPrototype()->class('submit');
		$form->onSubmit[] = array($this, 'editLanguageFormSubmitted');

		return $form;
	}

	public function editLanguageFormSubmitted(AppForm $form){
		$values = $form->getValues();

		if(!is_numeric($values["id_language"])){
			$this->system->addLanguage($values);
			$this->flashMessage("Jazyk byl přidán.", 'ok');
		}else{
			$this->system->editLanguage($values);
			$this->flashMessage("Jazyk byl upraven.", 'ok');
		}

		$this->redirect('System:viewLanguages');

	}

	public function actionViewOptions(){

		$this->template->title = "Nastavení systému";
		$this->template->form = $this->getComponent('editOptions');

	}

	protected function createComponentEditOptions(){

		$form = new AppForm;

		$form->addText('sess_exp', 'Čas odhlášení:')->setDefaultValue($this->system->getOptionVariable("sess_exp"))
		->addRule(Form::FILLED, 'Musí být nastaven čas.')
		->addCondition(Form::FILLED);
		
		$form->addTextArea('seo_description', 'Description:')->setDefaultValue($this->system->getOptionVariable("seo_description"))
		->addRule(Form::FILLED, 'Musí být nastaven popis stránky.')
		->addCondition(Form::FILLED);
		
		$form->addText('seo_keywords', 'Keywords:')->setDefaultValue($this->system->getOptionVariable("seo_keywords"))
		->addRule(Form::FILLED, 'Musí být nastaven popis stránky.')
		->addCondition(Form::FILLED);

		$form->addSubmit('confirm', 'Uložit')->getControlPrototype()->class('ok');
		$form->onSubmit[] = array($this, 'editOptionsFormSubmitted');

		return $form;
	}

	public function editOptionsFormSubmitted(AppForm $form){
		$values = $form->getValues();

		$this->system->saveOptions($values);
		$this->flashMessage("Nastavení bylo uloženo.", 'ok');
		$this->redirect('System:viewOptions');

	}
	
	public function actionViewFiles(){

		$this->template->files = $this->fileHTML($this->system->getFiles($id_directory));
		$this->template->title = "Správa souborů";
	}
	
	public function fileHTML($files){

		if($files["id_directory"] != 0) $html = "<a class='normal' href='".$this->presenter->link("viewDirectory!")."' onclick='files.changeDirectory(this, ".(!empty($files["id_directory_parent"])?$files["id_directory_parent"]:"0")."); return false;'>Zpět</a>"; 
		$html .= "<input type='hidden' id='id_parent' value='{$files["id_directory"]}' />
				  <input type='hidden' id='dir_path' value='{$files["path"]}' />";
		
		$html .= "<br /><span>Nacházíte se: <strong>{$files["path"]}</strong></span> <br />";
		
		$html .= "<table class='datagrid' style='width: 100%;'>
				  <tr>
				  <th>Název</th>
				  <th style='width: 32px;'>Typ</th>
				  <th style='width: 64px;'>Velikost</th>
				  <th style='width: 64px;'>Úpravy</th>
				  </tr>";
		
		foreach($files["files"] as $f){
			$html .= "<tr>";
			$html .= "<td>";
			
			if(!empty($f["th_name"])) $html .= "<span class='file-thumb'><img style='width: 48px;' src='".$this->presenter->getPresenter()->template->baseUri."upload/".$f["path"].$f["th_name"]."' /></span>";
			
			$html .= ($f["type"] == "DIR" ?"<a href='".$this->presenter->getPresenter()->template->baseUri."admin/system/view-files/?do=viewDirectory' onclick='files.changeDirectory(this, ".$f["id_file"]."); return false;'><strong>":"<span class='fileFromSys'>")."{$f["custom_name"]}".($f["type"] == "DIR" ?"</strong></a>":"<input type='hidden' class='id_file' value='{$f["id_file"]}' /></span>")."</td>";
			$html .= "<td><img src='".$this->presenter->getPresenter()->template->baseUri.$this->system->formatType($f["type"])."' alt='{$f["type"]}' title='{$f["type"]}' /></td>";
			$html .= "<td>".($f["size"] != 0 ? $this->system->formatSize($f["size"]) : $this->system->formatSize($f["sized"]))."</td>";
			$html .= "<td>
						<a class='remove' href='".$this->presenter->link("deleteDir!")."' onclick='files.deleteDir(this,".$f["id_file"].");return false;'>&nbsp;</a>
						".($f["type"] != "DIR" ?"<a class='download' href='".$this->presenter->link("downloadFile", array("id_file" => $f["id_file"]))."'>&nbsp;</a>":"")."
					  </td>";
			$html .= "</tr>";
		}
		 
		if(count($files["files"]) == 0){
			$html .= "<tr>";
			$html .= "<td colspan='4' style='text-align: center;'>V tomto adresáři nejsou nahrány žádné soubory ani adresáře.</td>";
			$html .= "</tr>";
		}
		
		$html .= "</table>";
		
		return $html;
	}
	
	public function actionDownloadFile(){
		
		$file = $this->system->getFileById($_GET["id_file"]);
		
		$this->terminate(new DownloadResponse("upload/".$file[0]["path"].$file[0]["name"], $file[0]["custom_name"], 'contenttype'));
	}
	
	public function handleDeleteDir(){
		
		if(!empty($_GET["id_file"])) $this->system->deleteDirectory($_GET["id_file"], $this->presenter->getPresenter()->template->baseUri);
		$this->payload->files = $this->fileHTML($this->system->getFiles($_GET["id_parent"]));
	}
	
	public function handleCreateDir(){
		
		if(!empty($_GET["name"])) $this->system->saveDirectory($_GET["name"], $_GET["id_parent"]);
		$this->payload->files = $this->fileHTML($this->system->getFiles($_GET["id_parent"]));
	}
	
	public function handleViewDirectory(){
		
		$this->payload->files = $this->fileHTML($this->system->getFiles($_GET["id_file"]));
	}
	
	public function handleSaveFiles(){
		
		$this->system->saveFiles($_POST["files"], $_POST["id_parent"]);
		$this->flashMessage("Soubory byly uloženy.", 'ok');
		$this->payload->files = $this->fileHTML($this->system->getFiles($_POST["id_parent"]));
	}
	
	public function actionViewTranslations(){
		
		if(!empty($_POST["addKey"])){
			
			if(!empty($_POST["newKey"])){
				Translation::addTranslation($_POST["newKey"]);
				$this->flashMessage("Nový klíč byl uložen.", 'ok');	
			}else{
				$this->flashMessage("Zadejte název klíče.", 'error');	
			}
		}
		
		if(!empty($_POST["save"])){
			
			foreach($_POST["translation"] as $key => $value){
				Translation::editTranslation($key, $value, $this->session->admin_id_language);
			}
			$this->flashMessage("Překlady pro daný jazyk byly uloženy.", 'ok');	
		}
		
		$this->template->translations = Translation::getStaticTranslation($this->session->admin_id_language);
	}
}

?>
